<?php
/**
 * Created by PhpStorm.
 * User: alei
 * Date: 2017-11-04
 * Time: 16:47
 */
namespace App\Models\Traits;

use Illuminate\Support\Facades\DB;
use App\Models\Exceptions\DbException;

/**
 * 封装了基本的查询构造器方法，可以通过use BaseDBMethod;使用这些方法
 * Class BaseDBMethod
 * @package App\Models\Traits
 */
trait BaseDBMethod
{
	protected static function getConnObj()
	{
		return DB::connection(static::DATABASE_CONF);
	}

	protected static function getDBobj($disable_query_log=FALSE)
	{
		$connObj = self::getConnObj();
		if(FALSE === $disable_query_log) {
			return $connObj->table(static::TABLE_NAME);
		} elseif(TRUE === $disable_query_log) {
			$connObj->disableQueryLog();
			return $connObj->table(static::TABLE_NAME);
		}
	}

	public static function beginTransaction()
	{
		DB::connection(static::DATABASE_CONF)->beginTransaction();
	}

	public static function rollBack()
	{
		DB::connection(static::DATABASE_CONF)->rollBack();
	}

	public static function commit()
	{
		DB::connection(static::DATABASE_CONF)->commit();
	}

	/**
	 * 创建或批量创建
	 * @param array $data
	 * @return mixed
	 */
	public static function batchCreate(& $data, $disable_query_log=FALSE)
	{
		return self::getDBobj($disable_query_log)->insert($data);
	}

	public static function insertGetId(& $data, $disable_query_log=FALSE)
	{
		return self::getDBobj($disable_query_log)->insertGetId($data);
	}

	public static function truncate($disable_query_log=FALSE)
	{
		return self::getDBobj($disable_query_log)->truncate();
	}

	/**
	 * 获取一列的值
	 * @param $value
	 * @return mixed
	 */
	public static function pluck($value, $disable_query_log=FALSE)
	{
		return self::getDBobj($disable_query_log)->pluck($value);
	}

	public static function limit($start, $limit = 0)
	{
		$limit = intval($limit > 0 ? $limit : 0);
		$start = intval($start > 0 ? $start : 0);
		if ($start > 0 && $limit > 0) {
			return " LIMIT $start, $limit";
		} elseif ($limit) {
			return " LIMIT $limit";
		} elseif ($start) {
			return " LIMIT $start";
		} else {
			return '';
		}
	}

	public static function result_first($sql, $param)
	{
		$result = self::getConnObj()->select($sql, $param);
		if($result && isset($result[0])) {
			return $result[0];
		}
		return null;
	}

//	public function __call($method, $param)
//	{
//		//TODO
//		throw new \Exception("{$method} is not found.");
//	}
//
//	static function __callStatic($method, $param)
//	{
//		//TODO
//		throw new \Exception("{$method} is not found.");
//	}
}